package org.example.controller;

import org.example.service.CakeCatelogService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Result;
import org.example.bean.CakeCatalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.example.utils.Results;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
public class CakeCatalogController {

    private CakeCatelogService cakecatalogService;

    @Autowired
    public void setCatalogService(CakeCatelogService cakecatalogService) {
        this.cakecatalogService = cakecatalogService;
    }

    /**
     * 添加分类信息
     * @param param
     * @return
     */
    @ResponseBody
    @PostMapping("/addCatalog")
    public Results addCatalogServlet(String param) {
        JSONArray json = JSON.parseArray(param);
        // System.out.println(json);
        List<CakeCatalog> list = new ArrayList<>();
        Iterator<Object> it = json.iterator();
        while(it.hasNext()) {
            // System.out.println(it.next());
            JSONObject next = (JSONObject)it.next();
            CakeCatalog cata = new CakeCatalog();
            // title 分类名称
            cata.setTitle(next.getString("title"));
            // info 分类信息
            cata.setInfo(next.getString("info"));
            // type 所属父类 需要得出 level_id 和 parent_id
            String type = next.getString("type");
            CakeCatalog father = cakecatalogService.selectByTitle(type);
            cata.setLevel_id(father.getLevel_id() + 1);
            cata.setParent_id(father.getId());
            list.add(cata);
        }
        cakecatalogService.insert(list);
        Results res = new Results();
        res.flag = 1;
        res.result = "/catalog_list";
        return res;
    }

    /**
     * 获取分类信息
     * @return
     */
    @ResponseBody
    @PostMapping("/catalogList")
    public Results catalogListServlet() {
        List<CakeCatalog> catalogs = cakecatalogService.selectAll();
        Results res = new Results();
        res.results = catalogs;
        return res;
    }

    /**
     * 删除分类信息
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delCatalog")
    public Results delCatalogServlet(String id) {
        List<Integer> list = cakecatalogService.findChildren(Integer.parseInt(id));
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) {
            cakecatalogService.delete(it.next());
        }
        Results res = new Results();
        res.flag = 1;
        res.result = list;
        return res;
    }

}
